/**
 * Place view uses a carousel widget to show information, reviews and a map of a single place.
 */

(function() {
	var view = View("place-view");

	var templates = {
		details: sprintf('<div class="details">'+
			'	#{displayimage}'+
			'	<div class="info">'+
			'		<div class="address">#{displayaddress}</div>'+
			'		<div class="rating">#{displayrating}</div>'+
			'		#{displaycallto}'+
			'		#{displayurl}'+
			'		<h2>%s</h2>'+
			'		<p>#{displayopeninghours}</p>'+
			'	</div>'+
			'</div>', qype.strings.openingHours),
        review: '<div class="review">'+
            '	<div class="subject" id="#{idSummary}" onclick="mwl.hide(\'##{idSummary}\');mwl.show(\'##{idFullText}\');">#{summary}</div>'+
            '	<div class="fullText" id="#{idFullText}" onclick="mwl.hide(\'##{idFullText}\');mwl.show(\'##{idSummary}\');" style="display: none;">#{fullText}</div>'+
            '	<div class="rating">#{stars}</div>'+
            '</div>'
	};
	
	qype.views.placeView = view;
	
	var toggle;
	var loading;
	var header;
	var carousel;
	var description;
	var reviews;
	var reviewsList;
	var reviewsLoading;
	var map;
	var mapImage;

	view.getHtml = function() {
		return sprintf('<div id="%s"></div>', view.getId());
	};

	var backId = view.getId() + "-back";

	function getCarouselLinks(index) {
		var data = {};
		data.prevOnclick = "mwl.iterateClass('#place-carousel-table','carousel-view', 'prev', '3', 'true', '');mwl.iterateClass('#place-carousel-table','carousel-320-view', 'prev', '3', 'true', '');";
		data.nextOnclick = "mwl.iterateClass('#place-carousel-table','carousel-view', 'next', '3', 'true', '');mwl.iterateClass('#place-carousel-table','carousel-320-view', 'next', '3', 'true', '');";
		if(index == 0) {
			data.prevName = qype.strings.prev + qype.strings.map;
			data.nextName = qype.strings.reviews + qype.strings.next;
		} else if(index == 1) {
			data.prevName = qype.strings.prev + qype.strings.info;
			data.nextName = qype.strings.map + qype.strings.next;
		} else if(index == 2) {
			data.prevName = qype.strings.prev + qype.strings.reviews;
			data.nextName = qype.strings.info + qype.strings.next;
		}
		
		return util.template('<div class="place-links"><table summary="Tabs" cellspacing="0" cellpadding="0" border="0"><tr>' +
			'<td><div class="prev"><a href="#" onclick="#{prevOnclick}">#{prevName}</a></div></td>' +
			'<td><div class="next"><a href="#" onclick="#{nextOnclick}">#{nextName}</a></div></td>' +
			'</tr></table></div>', data);
	}
	
	view.init = function() {
		this.initBack();
		toggle = ToggleWidget();
		view.getContainer().append(toggle.getHtml());
		loading = LoadingWidget({label: qype.strings.loading});
		toggle.setContent(0, "<h1>&nbsp;</h1>" + loading.getHtml());
		header = ElementWidget({id: view.getId() + "-header", tag: "h1"});
		carousel = CarouselWidget({id: "place-carousel"});
		toggle.setContent(1, header.getHtml() + carousel.getHtml());
		description = ElementWidget({id: "place-description"});
		carousel.addView(getCarouselLinks(0) + description.getHtml());
		reviews = ElementWidget({id: "place-reviews"});
		carousel.addView(getCarouselLinks(1) + reviews.getHtml());
		reviewsList = ListWidget({id: "place-reviews-list", emptyContent: sprintf('<div class="no-results">%s</div>', qype.strings.place_no_reviews)});
		reviewsLoading = LoadingWidget({label: qype.strings.loading});
		reviews.html(sprintf('<h2>%s</h2>', qype.strings.reviews) + reviewsList.getHtml() + reviewsLoading.getHtml());
		reviewsList.hide();
		reviewsLoading.show();
		map = ElementWidget({id: "place-map"});
		carousel.addView(getCarouselLinks(2) + sprintf('<h2>%s</h2>', qype.strings.map) + map.getHtml());
	};
	
	view.setLinks = function(links) {
		this.addBack(backId, links.backToPlaces);
		this.showBack(backId);
	};
	
	view.loadPlace = function(placedata) {
		function cleanNumber(number) {
			number = number || "";
			number = number.replace(/[^0-9+]/g,"");
			var hasPlus = number.match(/^\+/);
			number = number.replace(/[^0-9]/g,"");
			return (hasPlus ? "+" : "") + number;
		}
		
		var place = qype.models.PlaceModel(placedata);

        placedata.displayimage = placedata.image ? "<div class=\"image\"><img src='" + place.getImageUrl("medium2x") + "' class='main' /></div>" : "";
		if(placedata.address) placedata.displayaddress = sprintf('<div class="line">%s %s</div><div class="line">%s %s</div>', 
			placedata.address.housenumber || "", placedata.address.street || "", 
			placedata.address.postcode || "", placedata.address.city || "");
		placedata.displayopeninghours = (placedata.opening_hours || qype.strings.notAvailable).replace("\n","<br />");

		placedata.displayrating = '<div class="image-holder"><img class="stars'+placedata.average_rating+'" src="img/star.png" /></div>' + place.getReviewsStr();

		var phoneClean = cleanNumber(placedata.phone);
		if(phoneClean) placedata.displaycallto = '<div class="link call"><a href="tel:' + phoneClean + '"">' + qype.strings.place_call + ' (' + placedata.phone + ')</a></div>';
		if(placedata.url) placedata.displayurl = '<div class="link url"><a href="' + placedata.url + '">' + qype.strings.place_open_www + '</a></div>';

		header.html(placedata.title);
		carousel.showView(0);
		description.html(util.template(templates.details, placedata));
		reviewsList.populate([]);
		if(place.getReviewsCount() > 0) {
			reviewsList.hide();
			reviewsLoading.show();
			this.loadReviews(place.getId(), place.contentLang);
		} else {
			reviewsList.show();
			reviewsLoading.hide();
		}
		if(placedata.point) {
			var loc = placedata.point.split(',');
			map.html(sprintf('<img src="%s"/>', new OviMap({
				center : { lat : loc[0] , lon : loc[1] }, 
				zoom : 15, 
			    overlays : { scale : false, dot : true },
				size : { width : util.width(), height : 240 } 
			}).getUrl()));
		} else {
			map.html(qype.strings.noLocation);
		}
		toggle.showContent(1);
	};
	
	function reviewsToListItems(reviews) {
		return $.map(reviews, function(item, index) {
			var review = item.review;
			var content = util.template(templates.review, {
				summary: "<p>" + review.summary + "</p>",
				fullText: review.content_xhtml,
				idSummary: review.id + "-summary",
				idFullText: review.id + "-fullText",
				stars: '<div class="image-holder"><img class="stars' + review.rating + '" src="img/star.png" /></div>'
			});
			return {content: content};
		});
	}
	
	view.loadReviews = function(placeId, placeLang) {
		qype.API.get("places", {
	        onSuccess: function(response) {
				reviewsList.populate(reviewsToListItems(response.results));
				reviewsList.show();
				reviewsLoading.hide();
	        },
	        onFailure: function(response, status) {
				reviewsList.populate([]);
				reviewsList.hide();
				reviewsLoading.setError(util.networkErrorMessage(status, reviewsLoading.showLoadingMwl() + sprintf("qype.views.placeView.loadReviews.call(qype.views.placeView,'%s','%s');", placeId, placeLang)));
				reviewsLoading.showError();
				reviewsLoading.show();
	        }
		}, placeId + '/reviews/' + placeLang);
	};
	
	view.resetMwl = function() {
		return toggle.showContentMwl(0) + reviewsLoading.showLoadingMwl();
	};
	
})();
